package com.g9.blog.service.impl;

import com.g9.blog.common.Response;
import com.g9.blog.common.Result;
import com.g9.blog.doto.ArticleDoto;
import com.g9.blog.entity.Article;
import com.g9.blog.entity.ArticleContent;
import com.g9.blog.entity.Articleimg;
import com.g9.blog.entity.Users;
import com.g9.blog.repository.ArticleRepository;
import com.g9.blog.repository.ArticleimgRepository;
import com.g9.blog.repository.ContentRepository;
import com.g9.blog.repository.LikeRepository;
import com.g9.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: Graycat
 * @Date: 2020/9/11 11:09
 * Create by lwj.
 */

@Service
@Transactional
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleRepository articleRepository;
    @Autowired
    ContentRepository contentRepository;
    @Autowired
    LikeRepository likeRepository;
    @Autowired
    ArticleimgRepository articleimgRepository;

    public Result createOrUpdataArtile(ArticleDoto articleDoto ){
        // 根据封装得doto对象获取前端传来得json数据---
        ArticleContent content = articleDoto.getArticleContent();
        Article article = articleDoto.getArticle();
        // 先建立内容，再建文章，不然数据库会出错。
        ArticleContent temp = contentRepository.save(content);
        article.setContentId(temp.getId());
        articleRepository.save(article);
        return Response.makeOKRsp("保存文章成功。");
    }

    public List<Article> getUserLikeArticleByUserId(int userId ){
        List<Article> articleList = likeRepository.findAllArticleByUserId(userId);
//        System.out.println(articleList);
        return articleList;
    }

    @Override
    public List<Users> getLikeUserByArticleId(int articleId) {
        List<Users> userList = likeRepository.findAllUserByArticleId(articleId);
        return userList;
    }

    @Override
    public void deleteById( int id ) {
        articleRepository.deleteById(id);
    }

    @Override
    public List<Article> findAllById(int articleId) {
        return articleRepository.findAllById(articleId);
    }

    @Override
    public void save(Article article) {
        articleRepository.save(article);
    }

    public List<Article> findAllArticle() {
        return articleRepository.findAll();
    }

    public List<Article> findAllArticleByUserId(int userid) {
        return articleRepository.findAllByUserId(userid);
    }

    public List<Article> findAllArticleById(int articleId) {
        return articleRepository.findAllById(articleId);
    }

    public List<Articleimg> findAllImgByArticleId( int articleId ) {
        List<Articleimg> imgList = articleimgRepository.findAllByArticleId(articleId);
        return imgList;
    }
}
